package com.kevin.utilits.zookeeper;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;


public class ZookeeperService {
	private static Logger logger = Logger.getLogger(ZookeeperService.class);
	private ZooKeeper zooKeeper = null;
	
	ZookeeperService(String connectString){
		try {
			init(connectString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void init(String connectString) throws IOException{
		zooKeeper = new ZooKeeper("localhost:2181", 100000, null);
	}
	
	public void setData(String path, byte data[], int version) throws KeeperException, InterruptedException{
		zooKeeper.setData(path, data, version);
	}
	
	public void create(String path, String data) throws KeeperException, InterruptedException{
		zooKeeper.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}

	public void close() {
		try {
			if (null == zooKeeper) {
				return;
			}
			zooKeeper.close();
		} catch (InterruptedException e) {
			logger.error(e.getMessage(), e);
		}
	}
	public static void main(String[] args){
		ZookeeperService zookeeper = new ZookeeperService("127.0.0.1:2183");
		try {
			// zookeeper.isExist("/main-1", true);
			// zookeeper.create("/aaa", "best");
			zookeeper.create("/aaa/aaa", "best");
			// zookeeper.close();
			 NodeWatcher nodeWatcher = zookeeper.new NodeWatcher();
			 zookeeper.isExist("/aaa/aaa", nodeWatcher);
			// zookeeper.create("/aaa/aaa/aaa2", "best");
			// zookeeper.create("/aaa/aaa/aaa/4", "best");
			zookeeper.setData("/aaa/aaa", "2222223".getBytes(), 1);
			zookeeper.setData("/aaa/aaa", "2222223".getBytes(), 1);
			// for(int i=0;i<100;i++){
			// zookeeper.create("/main-" + i, "best" + i);
			// }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	public boolean isExist(String path) {
		Stat stat;
		try {
			stat = zooKeeper.exists(path, false);
			if(stat == null){
				return false;
			}else{
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean isExist(String path, boolean isWatch) {
		Stat stat;
		try {
			stat = zooKeeper.exists(path, isWatch);
			if (stat == null) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean isExist(String path, Watcher watcher) {
		Stat stat;
		try {
			stat = zooKeeper.exists(path, watcher);
			if (stat == null) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public class NodeWatcher implements Watcher {

		@Override
		public void process(WatchedEvent event) {
			System.out.print(event.getPath());
		}

	}
}

